﻿using System;
using Amazon.S3;
using Amazon.S3.Model;

namespace ICommonLibrary.Aws {

    public class S3Util {

        public static void CopyBucket(AmazonS3 s3, string sourceBucket, string destinationBucket, S3CannedACL cannedAcl) {
            using (ListObjectsResponse response = s3.ListObjects(new ListObjectsRequest() { BucketName = sourceBucket })) {
                foreach (S3Object obj in response.S3Objects) {
                    s3.CopyObject(new CopyObjectRequest {
                        SourceBucket = sourceBucket,
                        SourceKey = obj.Key,
                        DestinationBucket = destinationBucket,
                        DestinationKey = obj.Key,
                        CannedACL = cannedAcl
                    });
                }
            }
        }

        public static void ChangeKeys(AmazonS3 s3, 
                                      string bucket,
                                      S3CannedACL cannedAcl, 
                                      string keyPrefix,
                                      Func<string, string> keyChanger) {

            using (ListObjectsResponse response = s3.ListObjects(new ListObjectsRequest { BucketName = bucket, Prefix = keyPrefix})) {
                foreach (S3Object obj in response.S3Objects) {
                    if (obj.Key.EndsWith("/")) { // folder??
                        continue;
                    }
                    var newKey = keyChanger(obj.Key);

                    if (newKey.Equals(obj.Key)) {
                        continue;
                    }

                    s3.CopyObject(new CopyObjectRequest {
                        SourceBucket = bucket,
                        SourceKey = obj.Key,
                        DestinationBucket = bucket,
                        DestinationKey = newKey,
                        CannedACL = cannedAcl
                    });

                    s3.DeleteObject(new DeleteObjectRequest {
                        BucketName = bucket,
                        Key = obj.Key
                    });
                }
            }
        } 
    }
}